package org.lds.message.center.client.autoconfigure;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.lds.message.center.client.constant.ClientConstant;
import org.lds.message.center.client.properties.MessageCenterGrpcClientProperties;
import org.lds.message.center.service.grpc.MessageCenterServiceGrpc;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@ConditionalOnProperty(prefix = ClientConstant.GRPC_CLIENT_PREFIX, name = "enabled", havingValue = "true")
@EnableConfigurationProperties({MessageCenterGrpcClientProperties.class})
public class MessageCenterGrpcClientAutoConfiguration {
    private final MessageCenterGrpcClientProperties grpcClientProperties;
    private final ManagedChannel channel;

    public MessageCenterGrpcClientAutoConfiguration(MessageCenterGrpcClientProperties grpcClientProperties) {
        this.grpcClientProperties = grpcClientProperties;
        this.channel = ManagedChannelBuilder.forAddress(grpcClientProperties.getHost(), grpcClientProperties.getPort())
                .usePlaintext()
                .build();
    }

    @Bean
    public MessageCenterServiceGrpc.MessageCenterServiceBlockingStub messageCenterServiceBlockingStub() {
        return MessageCenterServiceGrpc.newBlockingStub(channel);
    }

    @Bean
    public MessageCenterServiceGrpc.MessageCenterServiceStub messageCenterServiceStub() {
        return MessageCenterServiceGrpc.newStub(channel);
    }

}
